package com.bwie.service.impl;

import cn.hutool.core.io.file.FileNameUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.ServiceItem;
import com.bwie.service.ServiceItemService;
import com.bwie.mapper.ServiceItemMapper;
import com.bwie.utils.R;
import com.bwie.vo.PageInfoVo;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
* @author Yoo19
* @description 针对表【service_item】的数据库操作Service实现
* @createDate 2025-07-11 10:07:01
*/
@Service
public class ServiceItemServiceImpl extends ServiceImpl<ServiceItemMapper, ServiceItem>
    implements ServiceItemService{
    @Autowired
    private ServiceItemMapper serviceItemMapper;
    @Autowired
    FastFileStorageClient fastFileStorageClient;
    @Override
    public R getItemPage(PageInfoVo pageInfoVo) {
        Page<ServiceItem> page = new Page<>((pageInfoVo.getPageNum()), pageInfoVo.getPageSize());
        Page<ServiceItem> serviceItemPage = serviceItemMapper.getItemPage(page,pageInfoVo);
        return R.OK(serviceItemPage);
    }

    @Override
    public R addItem(ServiceItem serviceItem) {
        ServiceItem item = serviceItemMapper.selectOne(new LambdaQueryWrapper<ServiceItem>().eq(ServiceItem::getServiceName, serviceItem.getServiceName()));
        if(item != null){
            return R.ERROR(500,"该服务已存在请勿重复添加");
        }
        serviceItem.setCreateTime(new Date());
        serviceItem.setUpdateTime(new Date());
        serviceItemMapper.insert(serviceItem);
        return R.OK();
    }

    @Override
    public R upload(MultipartFile file) throws IOException {
        try {
            String filename = file.getOriginalFilename();
            String extName = FileNameUtil.extName(filename);
            StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), extName, null);
            String url = "http://192.168.80.192:8888/" + storePath.getFullPath();
            return R.OK(url);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.ERROR(500,"上传失败");

    }

    @Override
    public R getItemByTypeId(Integer typeId) {
        List<ServiceItem> serviceItems = serviceItemMapper.selectList(new LambdaQueryWrapper<ServiceItem>().eq(ServiceItem::getServiceTypeId, typeId));
        return R.OK(serviceItems);
    }
}




